package br.srv.full.faces.postalservices.converter;

import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import br.srv.full.geoProcessing.entities.localidades.Locale;
import br.srv.full.geoProcessing.entities.localidades.LocaleType;
import br.srv.full.serviceLocator.ServiceLocator;
import br.srv.full.virtual.postalServices.base.BeansManagerInvalidResultException;
import br.srv.full.virtual.postalServices.base.GeoInformationServices;

public class LocaleConverter  implements Converter {

	private final Log log = LogFactory.getLog(getClass());
	private static GeoInformationServices gis = ServiceLocator.getService(GeoInformationServices.class);
	private static final Map<String, Locale> cache = Collections.synchronizedMap(new TreeMap<String, Locale>());

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext,
	 *      javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext p_context, UIComponent p_component, String p_value) {
		Locale l_find = null;
		try {
			l_find = cache.get(p_value);
			if (l_find == null) {
				l_find = gis.findLocaleByName(p_value);
			}
		} catch (BeansManagerInvalidResultException e) {
			log.warn(e);
		}
		return l_find;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext,
	 *      javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(FacesContext p_context, UIComponent p_component, Object p_value) {
		if (p_value instanceof Locale) {
			String l_name = ((Locale) p_value).getName();
			cache.put(l_name, (Locale) p_value);
			return l_name;
		} else if (p_value != null) {
			return p_value.toString();
		} else
			return null;
	}

}
